import { useReminderStore } from '@/stores/reminder'
import dayjs from 'dayjs'

/**
 * 提醒管理器 - 用于自动化管理材料补充提醒
 */
export class ReminderManager {
  constructor() {
    this.reminderStore = useReminderStore()
  }

  /**
   * 检查案件材料完整性并创建提醒
   * @param {Object} caseData - 案件数据
   * @param {Array} requiredMaterials - 必需材料列表
   */
  checkCaseMaterials(caseData, requiredMaterials = []) {
    if (!caseData || !Array.isArray(requiredMaterials)) {
      return
    }

    // 检查每个必需材料
    requiredMaterials.forEach(material => {
      if (!material.uploaded || !material.complete) {
        this.createMaterialReminder(caseData, material)
      }
    })

    // 检查截止日期
    if (caseData.deadline) {
      this.checkDeadlineReminder(caseData)
    }
  }

  /**
   * 创建材料缺失提醒
   * @param {Object} caseData - 案件数据
   * @param {Object} materialData - 材料数据
   */
  createMaterialReminder(caseData, materialData) {
    // 检查是否已存在相同的提醒
    const existingReminder = this.reminderStore.activeReminders.find(r => 
      r.caseId === caseData.id && 
      r.materialId === materialData.id &&
      r.type === this.reminderStore.REMINDER_TYPES.MATERIAL_MISSING
    )

    if (existingReminder) {
      return // 避免重复创建
    }

    const reminderType = materialData.uploaded ? 
      this.reminderStore.REMINDER_TYPES.MATERIAL_INCOMPLETE : 
      this.reminderStore.REMINDER_TYPES.MATERIAL_MISSING

    const priority = this.calculateMaterialPriority(materialData, caseData)
    
    this.reminderStore.addReminder({
      type: reminderType,
      title: this.getMaterialReminderTitle(materialData, reminderType),
      message: this.getMaterialReminderMessage(caseData, materialData, reminderType),
      priority: priority,
      caseId: caseData.id,
      caseNumber: caseData.caseNumber,
      clientName: caseData.clientName,
      targetRole: this.getTargetRole(caseData, materialData),
      materialType: materialData.type,
      materialId: materialData.id,
      dueDate: materialData.dueDate || this.calculateMaterialDueDate(caseData),
      actions: this.getMaterialActions(caseData, materialData),
      metadata: {
        materialName: materialData.name,
        materialDescription: materialData.description,
        required: materialData.required,
        category: materialData.category
      }
    })
  }

  /**
   * 检查并创建截止日期提醒
   * @param {Object} caseData - 案件数据
   */
  checkDeadlineReminder(caseData) {
    const deadline = dayjs(caseData.deadline)
    const now = dayjs()
    const daysLeft = deadline.diff(now, 'day')

    // 创建截止日期提醒的条件
    const shouldCreateReminder = 
      daysLeft <= 7 && daysLeft >= 0 && // 7天内且未过期
      !this.reminderStore.activeReminders.find(r => 
        r.caseId === caseData.id && 
        r.type === this.reminderStore.REMINDER_TYPES.DEADLINE_APPROACHING
      )

    if (shouldCreateReminder) {
      this.reminderStore.createDeadlineReminder(caseData, daysLeft)
    }
  }

  /**
   * 材料上传后自动解决相关提醒
   * @param {string} caseId - 案件ID
   * @param {string} materialType - 材料类型
   * @param {Object} uploadInfo - 上传信息
   */
  onMaterialUploaded(caseId, materialType, uploadInfo = {}) {
    // 解决相关的材料提醒
    this.reminderStore.resolveCaseReminders(caseId, materialType)

    // 记录日志
    console.log(`[ReminderManager] Material uploaded for case ${caseId}, type: ${materialType}`)

    // 可以发送成功通知
    this.notifyMaterialUploadSuccess(caseId, materialType, uploadInfo)
  }

  /**
   * 批量检查多个案件的材料状态
   * @param {Array} cases - 案件列表
   */
  batchCheckCases(cases = []) {
    cases.forEach(caseData => {
      if (caseData.materials) {
        this.checkCaseMaterials(caseData, caseData.materials)
      }
    })
  }

  /**
   * 定期清理过期提醒
   */
  cleanupExpiredReminders() {
    // 清理已解决的提醒（7天后）
    this.reminderStore.cleanupResolvedReminders(7)

    // 清理过期的截止日期提醒
    this.reminderStore.reminders
      .filter(r => 
        r.type === this.reminderStore.REMINDER_TYPES.DEADLINE_APPROACHING &&
        r.dueDate && 
        dayjs().isAfter(dayjs(r.dueDate))
      )
      .forEach(r => {
        this.reminderStore.removeReminder(r.id)
      })
  }

  /**
   * 计算材料提醒优先级
   * @param {Object} materialData - 材料数据
   * @param {Object} caseData - 案件数据
   * @returns {string} 优先级
   */
  calculateMaterialPriority(materialData, caseData) {
    // 必需材料优先级更高
    if (materialData.required) {
      // 如果接近截止日期，设为紧急
      if (caseData.deadline) {
        const daysLeft = dayjs(caseData.deadline).diff(dayjs(), 'day')
        if (daysLeft <= 3) return this.reminderStore.PRIORITY_LEVELS.URGENT
        if (daysLeft <= 7) return this.reminderStore.PRIORITY_LEVELS.HIGH
      }
      return this.reminderStore.PRIORITY_LEVELS.HIGH
    }

    return this.reminderStore.PRIORITY_LEVELS.MEDIUM
  }

  /**
   * 获取材料提醒标题
   * @param {Object} materialData - 材料数据
   * @param {string} reminderType - 提醒类型
   * @returns {string} 标题
   */
  getMaterialReminderTitle(materialData, reminderType) {
    const typeMap = {
      [this.reminderStore.REMINDER_TYPES.MATERIAL_MISSING]: `缺少${materialData.name}`,
      [this.reminderStore.REMINDER_TYPES.MATERIAL_INCOMPLETE]: `${materialData.name}不完整`,
      [this.reminderStore.REMINDER_TYPES.MATERIAL_EXPIRED]: `${materialData.name}已过期`
    }
    
    return typeMap[reminderType] || '材料提醒'
  }

  /**
   * 获取材料提醒消息
   * @param {Object} caseData - 案件数据
   * @param {Object} materialData - 材料数据
   * @param {string} reminderType - 提醒类型
   * @returns {string} 消息内容
   */
  getMaterialReminderMessage(caseData, materialData, reminderType) {
    const baseMessage = `案件 ${caseData.caseNumber}`
    
    const messageMap = {
      [this.reminderStore.REMINDER_TYPES.MATERIAL_MISSING]: 
        `${baseMessage} 缺少必要材料"${materialData.name}"，请尽快上传`,
      [this.reminderStore.REMINDER_TYPES.MATERIAL_INCOMPLETE]: 
        `${baseMessage} 的材料"${materialData.name}"信息不完整，请补充完整`,
      [this.reminderStore.REMINDER_TYPES.MATERIAL_EXPIRED]: 
        `${baseMessage} 的材料"${materialData.name}"已过期，请重新提供`
    }
    
    return messageMap[reminderType] || `${baseMessage} 需要处理材料问题`
  }

  /**
   * 获取目标角色
   * @param {Object} caseData - 案件数据
   * @param {Object} materialData - 材料数据
   * @returns {string} 目标角色
   */
  getTargetRole(caseData, materialData) {
    // 一般情况下，材料提醒针对当事人
    if (materialData.targetRole) {
      return materialData.targetRole
    }
    
    // 根据材料类型判断
    if (materialData.category === 'legal' || materialData.category === 'internal') {
      return 'lawyer' // 法律文件或内部文件提醒律师
    }
    
    return 'client' // 默认提醒当事人
  }

  /**
   * 获取材料相关操作
   * @param {Object} caseData - 案件数据
   * @param {Object} materialData - 材料数据
   * @returns {Array} 操作列表
   */
  getMaterialActions(caseData, materialData) {
    const actions = []
    
    // 上传材料操作
    actions.push({
      type: 'upload',
      label: '上传材料',
      route: `/client/cases/${caseData.id}/materials?type=${materialData.type}`
    })
    
    // 联系律师操作
    if (caseData.assignedLawyer) {
      actions.push({
        type: 'contact',
        label: '联系律师',
        route: `/client/cases/${caseData.id}/contact`
      })
    }
    
    // 查看案件详情
    actions.push({
      type: 'view',
      label: '查看详情',
      route: `/client/cases/${caseData.id}`
    })
    
    return actions
  }

  /**
   * 计算材料截止日期
   * @param {Object} caseData - 案件数据
   * @returns {string} 截止日期
   */
  calculateMaterialDueDate(caseData) {
    if (caseData.deadline) {
      // 材料截止日期比案件截止日期提前3天
      return dayjs(caseData.deadline).subtract(3, 'day').format('YYYY-MM-DD')
    }
    
    // 默认7天后
    return dayjs().add(7, 'day').format('YYYY-MM-DD')
  }

  /**
   * 材料上传成功通知
   * @param {string} caseId - 案件ID
   * @param {string} materialType - 材料类型
   * @param {Object} uploadInfo - 上传信息
   */
  notifyMaterialUploadSuccess(caseId, materialType, uploadInfo) {
    // 可以在这里实现成功通知逻辑
    // 例如发送系统消息、邮件通知等
    console.log(`[ReminderManager] Material upload success notification sent for case ${caseId}`)
  }

  /**
   * 创建自定义提醒
   * @param {Object} reminderData - 提醒数据
   * @returns {string} 提醒ID
   */
  createCustomReminder(reminderData) {
    return this.reminderStore.addReminder(reminderData)
  }

  /**
   * 获取案件的所有提醒
   * @param {string} caseId - 案件ID
   * @returns {Array} 提醒列表
   */
  getCaseReminders(caseId) {
    return this.reminderStore.getRemindersByCase(caseId)
  }

  /**
   * 获取用户角色相关的提醒
   * @param {string} role - 用户角色
   * @returns {Array} 提醒列表
   */
  getUserReminders(role) {
    return this.reminderStore.getRemindersByRole(role)
  }
}

// 创建全局实例
export const reminderManager = new ReminderManager()

/**
 * 便捷函数 - 检查案件材料
 */
export function checkCaseMaterials(caseData, materials) {
  return reminderManager.checkCaseMaterials(caseData, materials)
}

/**
 * 便捷函数 - 材料上传完成
 */
export function onMaterialUploaded(caseId, materialType, uploadInfo) {
  return reminderManager.onMaterialUploaded(caseId, materialType, uploadInfo)
}

/**
 * 便捷函数 - 批量检查案件
 */
export function batchCheckCases(cases) {
  return reminderManager.batchCheckCases(cases)
}

/**
 * 便捷函数 - 清理过期提醒
 */
export function cleanupExpiredReminders() {
  return reminderManager.cleanupExpiredReminders()
}

export default reminderManager

